package com.sanji.pay.pay.web;

import com.sanji.pay.allinpay.util.SybUtil;
import com.sanji.pay.base.BaseResult;
import com.sanji.pay.common.utils.PayNumUtil;
import com.sanji.pay.pay.dto.PayDeal;
import com.sanji.pay.pay.entity.PayOrder;
import com.sanji.pay.pay.service.PayOrderService;
import com.sanji.pay.pay.vo.PayResult;
import com.sanji.pay.sys.domain.Account;
import com.sanji.pay.sys.repository.AccountRepository;
import com.sanji.pay.yeepay.pojo.YEEPayPojo;
import com.sanji.pay.yeepay.service.YeePayService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 接收商城的地址链接
 * Created by cbh on 2017/8/29.
 */
@Controller
@RequestMapping("/api/pay")
public class PayController {
  private static final Logger logger = Logger.getLogger(PayController.class);
  @Autowired
  private PayOrderService payOrderService;
  @Autowired
  private YeePayService yeePayService;
  @Autowired
  private AccountRepository accountRepository;

  @Value("${sj_mall.appkey}")
  public String sjMallAppKey;

  /**
   * 生成支付单
   * @param paramMap
   * {
   *   cusId: '商户号',
   *   appId: '应用id',
   *   memberId: '用户id，（钱包用户）',
   *   totalCost: '总金额',
   *   orderNum: '订单号',
   *   sourceType: '订单分类',
   *   validTime: '有效时间',
   * }
   * @return
   */
  @PostMapping("/addOrder")
  @ResponseBody
  public BaseResult createPayOrder(@RequestBody Map<String, String> paramMap){
    BaseResult baseResult = new BaseResult();
    TreeMap<String,String> params = new TreeMap<String,String>(paramMap);
    boolean isOK = true;
    String cusId = paramMap.get("cusId");
    String appId = paramMap.get("appId");
    //查询商户
    Account account = accountRepository.findByCusId(cusId);
    if (Objects.isNull(account) || !account.getAppId().equals(appId)){
      baseResult.setMsg("认证失败");
      baseResult.setSuccess(!isOK);
      return baseResult;
    }
    try {
      boolean isSign = SybUtil.validSign(params, account.getAppKey());// 接受到推送通知,首先验签
      if (!isSign){//验签完毕进行业务处理
        baseResult.setMsg("验签失败");
        baseResult.setSuccess(!isOK);
        return baseResult;
      }
      String memberId = paramMap.get("memberId");
      String amount = paramMap.get("totalCost");
      String orderNum = paramMap.get("orderNum");
      String sourceType = paramMap.get("sourceType");
      int validTime = Integer.valueOf(paramMap.get("validTime"));
      //是否货到付款
      String cod = paramMap.get("isCOD");
      cod = cod == null ? "true" : cod;
      PayOrder payorder = payOrderService.findByOrderNumAndSourceType(orderNum,sourceType);
      //验证参数不为空
      if(StringUtils.isEmpty(memberId) || StringUtils.isEmpty(amount) || StringUtils.isEmpty(orderNum)) {
        baseResult.setMsg("参数为空");
        baseResult.setSuccess(!isOK);
        return baseResult;
      }
      //生成支付单号
      String payNum = PayNumUtil.setPayNum();
      //保存支付单PayOrder
      payorder = payorder == null ? new PayOrder() : payorder;
      //商户号cusId存入 订单
      payorder.setCusId(cusId);
      payorder.setAmount(Integer.valueOf(amount));
      payorder.setCreateTime(new Date());
      payorder.setOrderNum(orderNum);
      payorder.setPayNum(payNum);
      payorder.setMemberId(memberId);
      payorder.setSourceType(sourceType);
      payorder.setValidTime(validTime);
      payorder.setCod(Boolean.parseBoolean(cod));
      switch (sourceType) {
        case "SJ_B2B":
          payorder.setVendorName("三际手机采购网");
          break;
        case "SJ_DIY":
          payorder.setVendorName("三际DIY手机壳");
          break;
        default:
          payorder.setVendorName(account.getName());
          break;
      }
      payorder.setStatus(PayOrder.PayStatus.UNPAY);
      payOrderService.save(payorder);
      baseResult.setMsg("保存成功");
      baseResult.setSuccess(isOK);
      return baseResult;
    } catch (Exception e) {
      baseResult.setMsg("保存出现异常");
      baseResult.setSuccess(!isOK);
      logger.error(e.getMessage());
      return baseResult;
    }
  }

  /**
   * 跳转到支付页面
   * @param orderNum 订单号
   * @param cusId 商户号
   * @param appId appId
   * @param sign 签名
   * @param model
   * @return
   * @throws Exception
   */
  @GetMapping()
  public String toPay(@RequestParam String orderNum,@RequestParam String cusId, @RequestParam String appId, @RequestParam String sign, Model model) throws Exception {
    logger.info("查看orderNum是否为空===============" + orderNum);
    PayOrder payOrder = payOrderService.findByOrderNum(orderNum);
    Account account = accountRepository.findByCusId(cusId);

    if (Objects.isNull(account) || !appId.equals(account.getAppId())){
      model.addAttribute("msg","认证失败");
      return "payment/404";
    }
    TreeMap<String,String> params = new TreeMap<>();
    params.put("orderNum",orderNum);
    params.put("cusId",cusId);
    params.put("appId",appId);
    params.put("sign",sign);
    boolean isSign = SybUtil.validSign(params, account.getAppKey());// 接受到推送通知,首先验签
    if (!isSign){//验签完毕进行业务处理
      model.addAttribute("msg","验签失败");
      return "payment/404";
    }
    if("未支付".equals(payOrder.getStatus().getName()) || "支付失败".equals(payOrder.getStatus().getName())){
      model.addAttribute("payNum", payOrder.getPayNum());
      model.addAttribute("amount", String.valueOf(payOrder.getAmount() / 100.00));
      String[] payTypes = account.getPayType().split(",");
      if(payOrder.isCod()){
        for (String payType :payTypes) {
          switch (payType){
            case "yeePay":
              model.addAttribute("yeePay",payType);
              break;
            case "AliPay":
              model.addAttribute("AliPay",payType);
              break;
            case "WeChat":
              model.addAttribute("WeChat",payType);
              break;
            case "wallet":
              model.addAttribute("wallet",payType);
              break;
            case "HDF":
              model.addAttribute("HDF",payType);
            default:
              break;
          }
        }
      }else{
        for (String payType :payTypes) {
          switch (payType){
            case "yeePay":
              model.addAttribute("yeePay",payType);
              break;
            case "AliPay":
              model.addAttribute("AliPay",payType);
              break;
            case "WeChat":
              model.addAttribute("WeChat",payType);
              break;
            case "wallet":
              model.addAttribute("wallet",payType);
              break;
            default:
              break;
          }
        }
      }
      //跳转支付页面判断支付方式
      return "payment/pay";
    }else{
      PayResult payResult = new PayResult();
      payResult.setCode("2");
      payResult.setMessage("您的订单已支付");
      model.addAttribute("result", payResult);
      return "payment/payment_result";
    }
  }

  /**
   * 测试回调
   * @param payNumber
   */
  @GetMapping("/callback")
  @ResponseBody
  public void testCallback(String payNumber){
    PayOrder payOrder = payOrderService.findByPayNumber(payNumber);
    PayDeal payDeal = new PayDeal();
    payDeal.setOrderNum(payOrder.getOrderNum());
    payDeal.setTotalCost(payOrder.getAmount());
    payDeal.setDealFee(payOrder.getAmount());
    payDeal.setDealState("0000");
    payDeal.setHmac("");
    payDeal.setDealId(payNumber);
    payDeal.setDealType("XS");
    payDeal.setPayTime(new Date());
    payDeal.setPayType("gateway");
    payDeal.setPayee("");
    payDeal.setBankCardNo("");
    payDeal.setBankCardName("");
    payDeal.setPayNum(payNumber);

    payOrderService.callbackToClient(payDeal,payOrder.getSourceType());
  }

  /**
   * E宝支付选择支付银行后或选择货到付款，跳转支付提交表单页面
   * @return
   */
  @PostMapping("/surePay")
  public String toYEEPay(String frpId,String payNumber,Model model){
    PayResult payResult = new PayResult();
    PayOrder payOrder = payOrderService.findByPayNumber(payNumber);
    if(frpId.equals("SJ_HDFK") && "未支付".equals(payOrder.getStatus().getName())){
      //通知商城并跳转页面
      PayDeal payDeal = new PayDeal();
      payDeal.setTotalCost(payOrder.getAmount());
      payDeal.setOrderNum(payOrder.getOrderNum());
      payDeal.setPayNum(payNumber);
      payDeal.setDealFee(payOrder.getAmount());
      payDeal.setHmac("");
      payDeal.setDealState("");
      payDeal.setDealType("");
      payDeal.setPayee("");
      payDeal.setBankCardNo("");
      payDeal.setBankCardName("");
      payDeal.setPayTime(null);
      payDeal.setPayType("gateway");
      String status = payOrderService.callbackToClient(payDeal,payOrder.getSourceType());
      if("success".equals(status)){
        payResult.setCode("1");
        payResult.setMessage("客官您已选择货到付款！我们会尽快安排发货，请耐心等待");
        //修改订单状态
        payOrder.setDealType("HDF");
        payOrder.setStatus(PayOrder.PayStatus.SUCCESS);
        payOrder.setPayment(1);
        payOrderService.save(payOrder);
      }else{
        payResult.setCode("2");
        payResult.setMessage("订单支付出现异常");
      }
      model.addAttribute("result",payResult);
      return "payment/payment_result";
    }else if("未支付".equals(payOrder.getStatus().getName())){
      YEEPayPojo yeePayPojo = yeePayService.getPayPOJO(payOrder,frpId);
      yeePayService.savePostYeePay(yeePayPojo);
      model.addAttribute("yeePayPojo",yeePayPojo);
      return "payment/yeePay";
    }else{
      payResult.setCode("2");
      payResult.setMessage("您的订单已支付");
      model.addAttribute("result",payResult);
      return "payment/payment_result";
    }
  }

  /**
   * 交易查询
   * @param param
   */
  @PostMapping("/query")
  public BaseResult queryPayOrder(@RequestBody Map param){
    TreeMap<String,String> params = new TreeMap<String,String>(param);
    BaseResult baseResult = new BaseResult();
    boolean isOK = true;
    try {
      boolean isSign = SybUtil.validSign(params, sjMallAppKey);// 接受到推送通知,首先验签
      if(isSign){
        String orderNum = params.get("orderNum");
        //查询订单，
        PayDeal payDeal = payOrderService.queryPayOrder(orderNum);
        baseResult.setSuccess(isOK);
        baseResult.setObj(payDeal);
        return baseResult;
      }else{
        baseResult.setMsg("验签失败");
        baseResult.setSuccess(!isOK);
        return baseResult;
      }
    } catch (Exception e){
      baseResult.setMsg("查询异常");
      baseResult.setSuccess(!isOK);
      return baseResult;
    }
  }
}
